import React from 'react';
import { Card, DatePicker } from 'antd';
import { ymd } from 'configs/constants';
import moment from 'moment';
import { nextTick } from 'utils/nextTick';
import { combineDate } from 'utils/share';


class Polyline extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
          value: moment()
        };
        this.onChange = this.onChange.bind(this);
    }

    componentDidMount(){
      const { queryTimeRangeGps, record } = this.props;
      const params = combineDate([ moment(), moment() ]);
      queryTimeRangeGps({ deviceNo: record.equipmentNo, ...params });
    }

    componentWillReceiveProps(next){
      console.log(next);
      if(typeof next.timeRangeGps !== 'undefined' ||
        next.timeRangeGps !== this.props.timeRangeGps){
        nextTick(() => {
          this.map = new window.BMap.Map('myMap1');
          // const { timeRangeGps } = next;
          const timeRangeGps = next.timeRangeGps || [];
          const itArr = [];
          timeRangeGps.forEach(item => {
            const point = new window.BMap.Point(item.longitude, item.latitude);
            itArr.push(point);
          });
          this.setState({ isShow: false });
          if(itArr.length){
            const point = new window.BMap.Point(itArr[0].lng, itArr[0].lat);
            this.map.centerAndZoom(point, 12);
            this.map.enableScrollWheelZoom(true);
            const polyLine = new window.BMap.Polyline(itArr, {
              strokeColor: 'red',
              strokeWeight: 2
            });
            this.map.addOverlay(polyLine);
            this.map.setViewport(itArr);
          }else{
            // message.warning('当日无轨迹');
            this.setState({ isShow: true });
            const point = new window.BMap.Point(116.404, 39.915);
            this.map.centerAndZoom(point, 9);
            this.map.enableScrollWheelZoom(true);
          }
        });
      }
    }

    onChange(value){
      const { queryTimeRangeGps, record, updateParent } = this.props;
      updateParent({ value });
      const params = combineDate([ value, value ]);
      queryTimeRangeGps({ deviceNo: record.equipmentNo, ...params });
    }

    render(){
      const { record, value } = this.props;
        return (
          <Card
            title={<div>设备轨迹 <span style={{ fontSize: 12 }}> 当前设备：{record.name}</span></div>}
            style={{ width: '100%', height: 500, position: 'relative', marginTop: 20 }}
            bodyStyle={{ padding: 0 }}
            extra={
              <DatePicker 
                placeholder="请选择时间"
                format={ymd}
                value={value}
                onChange={(params) => this.onChange(params)}
              />
            }
           >
            <div style={{ width: '100%', height: 430 }} id="myMap1" />
          </Card>
        );
    }
}

export default Polyline;